<?php

namespace App\Http\Controllers\App;

use App\Exceptions\ErrorException;
use App\Exceptions\FailException;
use App\Http\Controllers\Controller;
use App\Models\InviteCode;
use App\Models\Member;
use App\Models\MemberRecommend;
use App\Models\SmsMsg;
use App\Models\StoreRecommendMember;
use Faker\Provider\Uuid;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;


class AuthController extends Controller
{
    /**
     * 账号加密码登陆
     * @param Request $request
     * @return array
     * @throws FailException
     */
    public function login(Request $request)
    {
        $rules = [
            'phone' => ['required'],
            'password' => 'required|string|min:6|max:20'
        ];
        $message = [
            'required' => ':attribute不能为空',
            'min' => ':attribute不小于:min位',
            'max' => ':attribute不大于:max位',
        ];
        $attribute = [
            'phone' => '手机号',
            'password' => '密码'
        ];

        $validator = Validator::make($request->all(), $rules, $message, $attribute);

        if ($validator->fails()) {
            throw new FailException($validator->getMessageBag());
        }
        $member = Member::where("phone",$request->input("phone"))->first();
        if ($member == null) {

            throw new FailException("用户名不存在");
        }
        if (!password_verify($request->input("password"), $member->password)) {
            throw new FailException("用户名或密码错误");
        }

        return ['token' => Auth::guard('app')->fromUser($member), 'expire' => '2592000'];
    }

    /**
     * 手机登录
     * @param Request $request
     * @param SmsMsg $msg
     * @return \Illuminate\Http\Response
     * @throws FailException
     */
    public function phoneLogin(Request $request, SmsMsg $msg)
    {
        $this->validate($request,[
            'phone' =>[
                'required',
                'regex:/^1[345789][0-9]{9}$/',
            ],
            'code' => 'required',
        ], [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机格式错误',
            'code.required' => '验证码不能为空',
        ]);
        $phone = $request->input ( "phone" );
        $code = $request->input ( "code" );
        $msg->validate ( $phone, $code );
        $member = Member::where("phone", $phone)->first();
        if($member){
            return $this->renderJson(['token' => Auth::guard('app')->fromUser($member), 'expire' => '2592000']);
        }
        throw new FailException("该账号不存在请注册");

    }

    /**
     * 注册
     * @param Request $request
     * @return array
     * @throws ErrorException
     * @throws FailException
     */
    public function register(Request $request, SmsMsg $msg)
    {
        $rules = [
            'phone' => 'required|unique:members,phone',
            'password' => 'required|string|min:6|max:20',
            'code' => 'required'
        ];
        $message = [
            'required' => ':attribute不能为空',
            'min' => ':attribute不小于:min位',
            'max' => ':attribute不大于:max位',
            'unique' => ':attribute电话号码已存在',
        ];
        $attribute = [
            'phone' => '手机号',
            'password' => '密码',
            'code' =>   '验证码'
        ];
        $this->validate($request, $rules, $message, $attribute);

        $code = $request->input ( "code" );
        $msg->validate ( $request->input("phone"), $code );

        try{
            \DB::beginTransaction();
            $member = new Member;
            $member->phone = $request->input("phone");
            $member->password = bcrypt($request->input("password"));
            $member->uuid =  Uuid::uuid();
            $member->save();

            //todo 邀请会员
            $code = $request->input("invite_code");
            $invite_code = InviteCode::whereCode($code)->first();
            if (isset($invite_code)){
                if ($invite_code->target_type == 1){
                    // 商家邀请会员
                    $store_recommend_member = new StoreRecommendMember();
                    $store_recommend_member->store_id = $invite_code->target_id;
                    $store_recommend_member->member_id = $member->id;
                    $store_recommend_member->save();
                }else{
                    $member_recommend = new MemberRecommend();
                    $member_recommend->member_id = $invite_code->target_id;
                    $member_recommend->recommend_id = $member->id;
                    $member_recommend->save();
                }
            }

            \DB::commit();
            return ["token" => Auth::guard("app")->fromUser($member), "expire" => '2592000'];
        }catch (\Exception $exception){
            \Log::error ($exception);
            \DB::rollBack();
            throw new ErrorException('注册失败');
        }
    }

}